package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.SystemMessages;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.mapper.SystemMessagesMapper;
import cn.wolfcode.trip.base.mapper.TravelCommendMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommendServiceImpl implements ITravelCommendService {
    @Autowired
    private TravelCommendMapper travelCommendMapper;
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private SystemMessagesMapper systemMessagesMapper;

    public PageInfo<TravelCommend> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<TravelCommend> list = travelCommendMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void saveOrUpdate(TravelCommend entity) {
        //专门处理攻略推荐
        if (entity.getType() == TravelCommend.TYPE_STRATEGY) {
            //1:删除原来所有的攻略推荐
            travelCommendMapper.deleteAllTrategyCommend(TravelCommend.TYPE_STRATEGY);
            //2:保存当前新的推荐推荐
            travelCommendMapper.insert(entity);

            //根据id查询出待发布游记对象
            Travel travel = travelMapper.selectByPrimaryKey(entity.getTravelId());
            //查出当前作者id,并设置到系统通知界面

            systemMessagesMapper.insert( new SystemMessages(travel.getAuthor().getId(),"你好你的标题为:"+travel.getTitle()+"的游记,已被管理员设为推荐",new Date(),0));
            return;
        }

        if (entity.getId() == null) {
            travelCommendMapper.insert(entity);
            //根据id查询出待发布游记对象
            Travel travel = travelMapper.selectByPrimaryKey(entity.getTravelId());
            //查出当前作者id,并设置到系统通知界面

            systemMessagesMapper.insert( new SystemMessages(travel.getAuthor().getId(),"你好你的标题为:"+travel.getTitle()+"已被管理员设为推荐",new Date(),0));
        } else {
            travelCommendMapper.updateByPrimaryKey(entity);
        }
    }

    public List<TravelCommend> listCommend(Integer type) {
        Date beginDate = null;
        Date endDate = new Date();
        //设置好时间
        if (type == TravelCommend.TYPE_WEEK) {
            //设置当前周
            beginDate = DateUtil.getSevenDaysAgo(endDate);
        } else if (type == TravelCommend.TYPE_MONTH) {
            //当前当前月
            beginDate = DateUtil.getAMonthAgo(endDate);
        }
        return travelCommendMapper.selectCommendByType(type, beginDate, endDate);
    }
}
